<?php
ignore_user_abort();
class IndexAction extends Action {
    public function index(){
        header("Content-Type:text/html; charset=utf-8");
        	echo($_SERVER['REMOTE_ADDR']);
        
    }
    
    /**
     * 得到一个访问代理ip和关键词
     */
    function job(){
    	$ret = array();
    	$userModel = D('User');
		$userInfo = $userModel->getUserId($_REQUEST['username']);
    	if ($userInfo) {
    		if ($userInfo['usr_timeout']<time()) {
    			//到期
    			if (1==$userInfo['usr_type']) {
	    			$ret['msg'] = array('images/notification.png','您的服务到期','亲您的服务已经到期，请续费！');
    			}else {
	    			$ret['msg'] = array('images/notification.png','试用结束','试用7天已经结束，如果亲认为我们的软件很赞，请购买支持我们！');
    			}
    		}elseif (1==$userInfo['usr_type'] && $userInfo['usr_pw']!=$userModel->encrypt($_REQUEST['password'])) {
    			//验证码错误
    			$ret['errno'] = 1;
    			$ret['msg'] = array('images/notification.png','服务验证码错误','请重新输入服务验证码！');
    		}else {
    			//TODO 最大数量限制，试用每天50，付费每天100
		    	$todayTime = strtotime(date('Y-m-d 0:0:0'));
		    	$uid 	=	$userInfo['usr_id'];
		    	$logModel = D('Log');
		    	$agentModel = D('Agent');
		    	$keywords = $_REQUEST['keywords'];
		    	shuffle($keywords);
		    	
				$usedIps = $logModel->where("usr_id=$uid and log_datetime > $todayTime")->getField('log_id,agt_ip');//已经使用过的IP
				$completed = true;//所有任务已经完成
				foreach($keywords as $keyword){
					$cnt = $logModel->where(array(
						'usr_id' => $uid,
						'kw_name' => $keyword['name'],
						'log_datetime' => array('gt',$todayTime),
					))->count();
					
					//这个关键词还没有搜索次还没到，分配代理IP
					if($cnt < $keyword['cnt']){
						$completed = false;
						$sql = "agt_rank in (1,2,3) and agt_country='中国' and agt_province not in ('台湾','香港','澳门') and agt_err=0 ";
						if($usedIps){
							$sql .= sprintf(' AND agt_ip not in ("%s")',implode('","',$usedIps));
						}
						$ipInfo = $agentModel->where($sql)
											->order('rand()')
											->find();
						if($ipInfo){
							$ret	=	array(
								'proxy'	=>array(
									'scheme'=>	strtolower($ipInfo['agt_type']),
									'host'=> $ipInfo['agt_ip'],
									'port'=>	intval($ipInfo['agt_port']),
								),
								'keyword'	=> $keyword['name'],
							);
							$logModel->add(array(
								'usr_id'	=>$uid,
								'agt_ip'	=> $ipInfo['agt_ip'],
								'kw_name'	=> $keyword['name'],
								'log_datetime'	=>	time(),
							));
							if (empty($usedIps)) {
								$ret['msg'] = array('images/notification.png','开始踩流量了','奴家开始踩流量了！');
							} 
						}else {
							$ret['msg'] = array('images/notification.png','今天已经达到流量上限','今天已经达到流量上限，明天再来吧！');
						}
						break;
					}
		    	}
		    	if ($completed) {
		    		$ret['msg'] = array('images/notification.png','今天流量已经踩完','如果还想踩流量，请增加宝贝搜索关键词或增加搜索次数');
		    	}
    		}
    	}else {
    		$ret['msg'] = array('images/notification.png','今天免费试用名额已经用完','明天再来吧！');;
    	}
    	echo json_encode($ret);
    }
    
    function task() {
    	$ret = array();
    	$userModel = D('User');
		$userInfo = $userModel->getUserId($_REQUEST['sellername']);
		if(!$userInfo){
			$ret['msg'] = array('images/notification.png','今天免费试用名额已经用完','明天再来吧！');
		}elseif ($userInfo['usr_timeout']<time()) {
			//到期
			if (1==$userInfo['usr_type']) {
				$ret['msg'] = array('images/notification.png','您的服务到期','亲您的服务已经到期，请续费！');
			}else {
				$ret['msg'] = array('images/notification.png','试用结束','试用已经结束，如果亲认为我们的软件很赞，请购买支持我们！');
			}
		}elseif (1==$userInfo['usr_type'] && $userInfo['usr_pw']!=$userModel->encrypt($_REQUEST['password']) && false) {
			//验证码错误
			$ret['errno'] = 1;
			$ret['msg'] = array('images/notification.png','服务验证码错误','请重新输入服务验证码！');
		}elseif (empty($_REQUEST['keywordName'])){
			$ret['msg'] = array('images/notification.png','请输入宝贝搜索关键字','请输入宝贝搜索关键字！');
		}else {
			$todayTime = strtotime(date('Y-m-d 0:0:0'));
			$uid 	=	$userInfo['usr_id'];
			$logModel = D('Log');
			$agentModel = D('Agent');
			
			$usedIps = $logModel->where("usr_id=$uid and log_datetime > $todayTime")->getField('log_id,agt_ip');//已经使用过的IP
			//付费用户每天200个限制，试用用户100个每天
			if (count($usedIps)>100+100*$userModel->getProperty($userInfo['usr_property'],'pay')) {
				$ret['msg'] = array('images/notification.png','踩流量已经达到今日上限','今天的流量已经踩完，明天再来吧！');
			}
		}
		if (empty($ret['msg'])) {
			$keywords = array();
			foreach ($_REQUEST['keywordName'] as $i =>$v){
				if ($v) {
					$keywords[] = array(
						'name'=>$v,
						'cnt'=>$_REQUEST['keywordCnt'][$i]
					);
				}
			}
			if ($keywords) {
		    	shuffle($keywords);
				$completed = true;//所有任务已经完成
		    	foreach($keywords as $keyword){
		    		$cnt = $logModel->where(array(
		    				'usr_id' => $uid,
		    				'kw_name' => $keyword['name'],
		    				'log_datetime' => array('gt',$todayTime),
		    		))->count();
		    			
		    		//这个关键词还没有搜索次还没到，分配代理IP
		    		if($cnt < $keyword['cnt']){
		    			$completed = false;
		    			$sql = "agt_rank in (1,2,3) and agt_country='中国' and agt_province not in ('台湾','香港','澳门') and agt_err=0";
		    			if($usedIps){
		    				$sql .= sprintf(' AND agt_ip not in ("%s")',implode('","',$usedIps));
		    			}
		    			$ipInfo = $agentModel->where($sql)
		    			->order('rand()')
		    			->find();
		    			if($ipInfo){
		    				$ret	=	array(
		    						'proxy'	=>array(
		    								'scheme'=>	strtolower($ipInfo['agt_type']),
		    								'host'=> $ipInfo['agt_ip'],
		    								'port'=>	intval($ipInfo['agt_port']),
		    						),
		    						'keyword'	=> $keyword['name'],
		    						'sellername'=>$_REQUEST['sellername'],
		    				);
		    				$logModel->add(array(
		    						'usr_id'	=>$uid,
		    						'agt_ip'	=> $ipInfo['agt_ip'],
		    						'kw_name'	=> $keyword['name'],
		    						'log_datetime'	=>	time(),
		    				));
		    				if (empty($usedIps)) {
		    					$ret['msg'] = array('images/notification.png','开始踩流量了','奴家开始踩流量了！');
		    				}
		    			}else {
		    				$ret['msg'] = array('images/notification.png','今天已经达到流量上限','今天已经达到流量上限，明天再来吧！');
		    			}
		    			break;
		    		}
		    	}
		    	if ($completed) {
		    		$ret['msg'] = array('images/notification.png','今天流量已经踩完','如果还想踩流量，请增加宝贝搜索关键词或增加搜索次数');
		    	}
			}else {
				$ret['msg'] = array('images/notification.png','请输入宝贝搜索关键字','请输入宝贝搜索关键字！');
			}
	    	
		}
      //if(isset($ret['msg'])){
			exit(json_encode($ret));
      //}
		
    }
    
    function page() {
    	$userInfo = D('User')->getUserId($_REQUEST['sellername']);
    	if ($userInfo) {
    		$logData = D('Log')->where(array(
    			'agt_ip' =>	$_REQUEST['host'],
    			'usr_id' =>	$userInfo['usr_id'],
    			'log_datetime' => array('gt',strtotime(date('Y-m-d 0:0:0')))
    		))->find();
    		if ($logData) {
    			//TODO设置找到的页数，代理IP可用;
    		}
    	}
    }
    
    /**
     * 录入IP地址
     */
    function inip() {
    	if (!empty($_REQUEST['ips'])) {
		    $content = $_REQUEST['ips'];
		    $cnt = D('Agent')->saveTextIp($content);
		    if (!empty($_REQUEST['source'])) {
		    	Log::write("inip source is {$_REQUEST['source']} count is $cnt",Log::INFO);
		    }
    	}
   		$this->display();
    }
    
    /**
     * 得到IP用来验证等级
     */
    function getIp4check() {
    	$model = D('Agent');
		$muti	=	isset($_GET['muti']);
		$time = time()-3600*3;
		if (isset($_GET['re'])) {
			//检查已经在使用的是否已经失效
			$model->where("agt_rank in (1,2,3) and agt_country='中国' and agt_province not in ('台湾','香港','澳门') and agt_err=0 and agt_lasttime <".$time);
			$model->order($muti?'rand()':'agt_lasttime ASC');
			$item	= $model->find();
		}elseif (isset($_GET['reer'])){
			//对失效的代理再次查询
			$model->where("agt_rank in (1,2,3) and agt_country='中国' and agt_province not in ('台湾','香港','澳门') and agt_err<5 and agt_lasttime <".$time);
			$model->order($muti?'rand()':'agt_lasttime ASC');
			$item	= $model->find();
		}else{
			$item	=	$model->where("agt_lasttime + agt_err*3600*24 < $time and agt_rank<4 and agt_country='中国' and agt_province not in ('台湾','香港','澳门') AND (agt_rank>0 OR agt_err < 4)")->order($muti?'rand()':'agt_lasttime + agt_err*3600*24 ASC')->find();
		}
		if ($item) {
			echo json_encode($item);
			$model->save(array(
				'agt_id'=>$item['agt_id'],
				'agt_lasttime' => time(),
			));
		}else {
			echo json_decode(0);
		}
    }
    
    /**
     * 表示还可用
     */
    function alive() {
    	$model = D('Agent');
    	if (empty($_GET['agt_id'])) {
    		;
    	}else {
	    	$data	=	array(
	    		'agt_lasttime'	=>	time(),
	    		'agt_id' => $_GET['agt_id'],
	    		'agt_err'=>0,
	    	);
	    	$model->save($data);
    	}
    }
    
    function getMyProperty() {
    	$user = D('User')->getUserByName($_REQUEST['sellername']);
    	echo json_encode($user['usr_property']);
    }
    
    function setRank() {
    	$model = D('Agent');
    	$get = $_GET;
    	$data	=	array(
    		'agt_lasttime'	=>	time(),
    		'agt_id' => $get['agt_id'],
    	);
    	$get['agt_lasttime'] = time();
    	if (isset($get['agt_err'])) {
    		$data['agt_err']	=	array('exp','agt_err+1');
			$model->save($data);
    	}elseif ($get['agt_rank']){
    		$data['agt_err'] = 0;
    		$data['agt_rank'] = $get['agt_rank'];
			$model->save($data);
    	}
    }
}